package edu.ntu.im.p2ptrade;


public class LockManager {

	private static final String MYSELF = "MYSELF";

	private String currentTransactionId;

	private Boolean locked = false;

	private Object mutex = new Object();

	public static LockManager me;

	public static synchronized LockManager getInstance() {
		if (me == null) {
			me = new LockManager();
		}
		return me;
	}

	
	
	public boolean lockMySelf(){
		String transactionId = MYSELF;
		synchronized (mutex) {
			if (locked && currentTransactionId != null
					&& transactionId.equals(this.currentTransactionId)
					|| !locked) {
				this.locked =true;
				this.currentTransactionId = transactionId;
				return true;
			} else {
				return false;
			}
		}
	}
	
	public boolean lockMySelf(String transactionId){
//		String transactionId = MYSELF;
		synchronized (mutex) {
			if (locked && currentTransactionId != null
					&& transactionId.equals(this.currentTransactionId)
					|| !locked) {
				this.locked =true;
				this.currentTransactionId = transactionId;
				return true;
			} else {
				return false;
			}
		}
	}
	
	public void unlockMySelf(){
		this.unlockMySelf(MYSELF);
	}

	private void releaseLock() {
		synchronized (mutex) {
			this.currentTransactionId = null;
			this.locked = false;
		}
	}

	/*private void grantLock(String peer, String transactionId) {
		this.currentTransactionId = transactionId;
		this.locked = true;
//		GrantLock grantLock = new GrantLock(transactionId);
//		Util.transdferMessageToPeer(grantLock.getMessageToTransfer(),
//				peer);
	}*/

	/*private void denyLock(String peer, String transactionId) {
		DenyLock denyLock = new DenyLock(transactionId);
		Util.transdferMessageToPeer(denyLock.getMessageToTransfer(),
				peer);
	}*/

//	public void lockPeer(String peer, String transactionId) {
//		Lock lock = new Lock(transactionId);
//		Util
//				.transdferMessageToPeer(lock.getMessageToTransfer(), peer);
//	}

	public void unlockMySelf(String transactionId) {
		synchronized (mutex) {
			if (locked && transactionId.equals(this.currentTransactionId)) {
				this.releaseLock();
			}
		}
	}

	public String getCurrentTransactionId() {
		return currentTransactionId;
	}


	public Boolean getLocked() {
		return locked;
	}

	

}
